package produceBack;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;

import org.json.JSONObject;




public class produce {
	/*
	 * 数据库连接信息
	 */
	static String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	static String dbURL = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=produce_middle";
	static String userName = "sa";
	static String userPwd="root";
	
	/*
	 * 通用实例
	 */
	static Connection dbConn = null;
	static Statement stat = null;
	static PreparedStatement preparedStatement = null;
	static CallableStatement callableStatement = null;
	static ResultSet rs = null;
	
	public static void main(String[] args) {
		befor();

		String sql = "{?=call produce_proc(?)}";
		try {
			callableStatement = dbConn.prepareCall(sql);
			callableStatement.registerOutParameter(1, Types.INTEGER);
			callableStatement.registerOutParameter(2, Types.VARCHAR);
			System.out.println("正在监控数据表。。。。。。");
			while(true) {
				long start = System.currentTimeMillis();
				callableStatement.execute();
				int returnValue = callableStatement.getInt(1);
				if(returnValue==1) {
					String reslut = callableStatement.getString(2);
//					JSONObject jsonObject = new JSONObject(reslut);
//					System.err.println(jsonObject);
					System.err.println("数据:"+reslut+"**执行耗时："+ String.valueOf(System.currentTimeMillis()-start)+"ms!");
				}
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("调用失败失败！");
		}
	
		after();
	}
	
	
	
	/**
	 * 连接数据库
	 */
	public static void befor(){
		
		try
		{
			Class.forName(driverName);
			System.out.println("加载驱动成功！");
		}catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("加载驱动失败！");
		}
		try
		{
			 dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
			System.out.println("连接数据库成功！");
		}catch(Exception e)
		{
			e.printStackTrace();
			System.out.print("SQL Server连接失败！");
		}
		

	}
	
	/**
	 * 关闭连接
	 */
	public static void after(){
		if(dbConn != null){
			try {
				dbConn.close();
				System.out.println("数据库连接已断开！");
			} catch (SQLException e) {
				System.out.println("SQL Server关闭连接失败！");
				e.printStackTrace();
			}
		}
	}
	
}
